<?php
/**
 * 产品促销管理
 * @author cjli
 *
 */
class PromotionAction extends AdminAction
{
	public function index()
	{
		$this->wholesale_list();
	}
	
	//批发列表
	public function wholesale_list()
	{
		$product_name = trim($_POST['product_name']);
		if($product_name){
			$where['product_name'] = array('like', '%'.$product_name.'%');
		}
		$wholesale_db = D('product_wholesale');
		//分页
		$wholesale_db->where($where);
		$count = $wholesale_db->count();
		import("ORG.Util.Page");
		$Page = new Page($count,20);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		//批发数据
		$wholesale_db->field('id,product_name,rank_ids,display');
		$wholesale_db->order('id DESC');
		$wholesale_db->limit($Page->firstRow.','.$Page->listRows);
		$wholesale_db->where($where);
		$wholesaleList = $wholesale_db->select();
		$this->assign('wholesaleList', $wholesaleList);
		//会员等级
		$rankList = UserModel::getRankList();
		$this->assign('rankList', $rankList);
		
		$this->display('wholesale_list');
	}
	
	//添加批发
	public function wholesale_add()
	{
		if(isset($_POST['dosubmit']))
		{
			$product_id = intval($_POST['product_id']);
			if(!$product_id){
				$this->error('添加失败,产品不存在', U('promotion/wholesale_list'));
			}
//			$product_items_db = D('product_items');
//			$where = array(
//				'product_id' => $product_id,
//				'language_id' => C('language_id'),
//			);
//			$product_name = $product_items_db->where($where)->getField('name');
//			$data = array(
//				'product_id' => $product_id,
//				'product_name' => $product_name,
//				'display' => intval($_POST['display']),
//			);
//			//等级
//			if($_POST['rank_id']['0'] == 0){
//				$data['rank_ids'] = 0;
//			}else{
//				$data['rank_ids'] = join(',', $_POST['rank_id']);
//			}
//			//数量价格处理
//			$qtyArray = $_POST['qty'];
//			$priceArray = $_POST['price'];
//			$prices = array();
//			foreach ($qtyArray as $key => $qty){
//				if(intval($qty) == 0 || floatval($priceArray[$key]) ==0){
//					continue;
//				}
//				$prices[] = array(
//					'qty' => $qty,
//					'price' => $priceArray[$key],
//				);
//			}
//			if($prices){
//				$data['prices'] = serialize($prices);
//			}
//			
//			$wholesale_db = D('product_wholesale');
//			$lastId = $wholesale_db->add($data);
			$wholesale_id = PromotionModel::updateWholesaleInfo($_POST);
			if($wholesale_id){
				$this->success('批发方案添加成功', U('promotion/wholesale_list'));
			}else{
				$this->error('添加失败', U('promotion/wholesale_list'));
			}
		}else{
			$select_categorys = CategoryModel::categorySelectList(0); 
			$this->assign('select_categorys', $select_categorys);
			$brandsArray = array();
			$brands= CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			foreach ($brands as $cat){
				$brandsArray[$cat['id']] = $cat['name'];
			}
			$this->assign('brandsArray', $brandsArray);
			//会员等级
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
			$this->display('wholesale_add');
		}
	}
	
	//编辑批发方案
	public function wholesale_edit()
	{
		$wholesale_id = intval($_GET['wid']);
		$wholesale_db = D('product_wholesale');
		$wholesale_info = $wholesale_db->where('id='.$wholesale_id)->find();
		if(! $wholesale_info){
			$this->error('批发方案不存在！', U('promotion/wholesale_list'));
		}
		if(isset($_POST['dosubmit']))
		{
			$wholesale_id = PromotionModel::updateWholesaleInfo($_POST, $wholesale_id);
			if($wholesale_id){
				$this->success('批发方案编辑成功！', U('promotion/wholesale_list'));
			}else{
				$this->error('批发方案编辑失败！', U('promotion/wholesale_list'));
			}
		}else{
			$this->assign('wholesale', $wholesale_info);
			//会员等级
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
			$this->display('wholesale_edit');		
		}
	}
	
	//删除批发
	public function wholesale_delete()
	{
		$wid = intval($_GET['wid']);
		$wholesale_db = D('product_wholesale');
		$wholesale_info = $wholesale_db->where('id='.$wid)->find();
		if(! $wholesale_info){
			$this->error('批发方案不存在！', U('promotion/wholesale_list'));
		}
		$wholesale_db->delete($wid);
		S('wholesale_list', NULL);
		$this->success('批发方案删除成功！', U('promotion/wholesale_list'));
	}
	
	//红包列表
	public function bonus_list()
	{
		$bonus_db = D('bonus_type');
		//分页
		$count = $bonus_db->count();
		import("ORG.Util.Page");
		$Page = new Page($count,20);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		//批发数据
		$bonus_db->field('id,type_name,type_money,min_amount,send_type');
		$bonus_db->order('id DESC');
		$bonus_db->limit($Page->firstRow.','.$Page->listRows);
		$bonus_db->where($where);
		$bonusList = $bonus_db->select();
		
		$sendBonusArray = PromotionModel::getBounsSendCount();
		$useBonusArray = PromotionModel::getBounsUseCount();

		foreach ($bonusList as &$bonus){
			$bonus['send_count'] = isset($sendBonusArray[$bonus['id']]) ? $sendBonusArray[$bonus['id']] : 0;
			$bonus['use_count'] = isset($useBonusArray[$bonus['id']]) ? $useBonusArray[$bonus['id']] : 0;
		}
		$this->assign('bonusList', $bonusList);
		
		$this->display('bonus_list');
	}
	
	//红包发放
	public function bonus_send()
	{
		$bonus_id = intval($_GET['bonus_id']);
		if($_POST['dosubmit']){
			if($_POST['catid'] == 0){
				$this->error('请选择会员等级！');
			}
			//根据会员等级的ID获取用户列表
			$user_db = D('users');
			$userList = $user_db->field('id,email,username,language_id')->where('rank_id='.$_POST['catid'])->select();
			
			$bonusInfo = PromotionModel::getBonusInfo($bonus_id);
			
			foreach ($userList as $key => $val){
				$user_bonusdb = D('user_bonus');
				//先判断其是否存在
				$user_bonus = $user_bonusdb->field('id')->where('bonus_id='.$bonus_id.' AND user_id='.$val['id'])->find();
				if(!$user_bonus){
				
					$email_template = UserModel::getEmailTemplateInfo('bonusTypeEmail', $val['language_id']);
					//发邮件
					if($email_template){
						$mailInstance = D(WEB_APP_NAME.'://Email');
						$content = str_replace('{$username}', $val['username'], $email_template['content']);
						$content = str_replace('{$type_money}', $bonusInfo['type_money'], $content);
						if($bonusInfo['restrict'] > 0){
							if($val['language_id'] == 4)
								$unlimited = "无限期";
							else
								$unlimited = "unlimited";
						
							$content = str_replace('{$use_start_date}', $unlimited, $content);
							$content = str_replace('{$use_end_date}', $unlimited, $content);
						}else{
							$content = str_replace('{$use_start_date}', date('Y-m-d',$bonusInfo['use_start_date']), $content);
							$content = str_replace('{$use_end_date}', date('Y-m-d',$bonusInfo['use_end_date']), $content);
						}
						$content = $mailInstance->replaceMail($content);
						$title = $mailInstance->replaceMail($email_template['title']);
						if($mailInstance->sendMail($val['email'], $title, $content)){
							$emailed = 1;
						} else {
							$emailed = 0;
						}
						$data = array(
							'bonus_id' => intval($bonus_id),
							'bonus_sn' => 0,
							'user_id' => intval($val['id']),
							'used_time' => 0,
							'order_id' => 0,
							'emailed' => $emailed,//1：已发成功；0未成功
						);
						$user_bonus_id = $user_bonusdb->add($data);		
					}
				}	
			}
			S('user_bonus_list', NULL);
			$this->success('红包发放成功！', U('promotion/bonus_look_list','bonus_id=1'));
		}else{
			$bonusInfo = PromotionModel::getBonusInfo($bonus_id);
			//按用户发放
			if($bonusInfo['send_type'] == 0){
				//会员等级列表
				$rankList = UserModel::getRankList();
				//print_r($rankList);
				$this->assign('rankList', $rankList);
				$this->display('bonus_by_user');
			}
		}
		
	}
	
	//查看发放的红包
	public function bonus_look_list()
	{
		$bonus_id = intval($_GET['bonus_id']);
		$bonusInfo = PromotionModel::getBonusInfo($bonus_id);
		//按用户发放
		if($bonusInfo['send_type'] == 0){
			$bonusList = PromotionModel::getBonusList($bonus_id);
		}elseif($bonusInfo['send_type'] == 2){//按生日发送红包
			//先判断用户是否填写自己的生日日期
			$time = date("m-d");    //取得当前月日
			$users_db = D('users');
			$users = $users_db->field('id,birthday,email,username,language_id')->where('birthday !=""')->select();
			if($users){
				foreach ($users as $var){
					$user_bonusdb = D('user_bonus');
					//先判断其是否存在
					$time1 = date("Y");
					$time2 = date("Y")+1;
					$begintimeall=strtotime($time1."-01-01");
					$endtimeall=strtotime($time2."-01-01");                                                         
					$user_bonus = $user_bonusdb->field('id')->where('bonus_id='.$bonus_id.' AND user_id='.$var['id'].' AND time BETWEEN '.$begintimeall.' AND '.$endtimeall)->find();
					if(!$user_bonus){
						$birthday = date("m-d",strtotime($var['birthday']));    //取得数据库月日
						if ($time == $birthday)
						{
							$email_template = UserModel::getEmailTemplateInfo('bonusTypeEmail', $var['language_id']);
							//发邮件
							if($email_template){
								$mailInstance = D(WEB_APP_NAME.'://Email');
								$content = str_replace('{$username}', $var['username'], $email_template['content']);
								$content = str_replace('{$type_money}', $bonusInfo['type_money'], $content);
								if($bonusInfo['restrict'] > 0){
									if($var['language_id'] == 4)
										$unlimited = "无限期";
									else
										$unlimited = "unlimited";
								
									$content = str_replace('{$use_start_date}', $unlimited, $content);
									$content = str_replace('{$use_end_date}', $unlimited, $content);
								}else{
									$content = str_replace('{$use_start_date}', date('Y-m-d',$bonusInfo['use_start_date']), $content);
									$content = str_replace('{$use_end_date}', date('Y-m-d',$bonusInfo['use_end_date']), $content);
								}
								$content = $mailInstance->replaceMail($content);
								$title = $mailInstance->replaceMail($email_template['title']);
								if($mailInstance->sendMail($var['email'], $title, $content)){
									$emailed = 1;
								} else {
									$emailed = 0;
								}
								$data = array(
									'bonus_id' => intval($bonus_id),
									'bonus_sn' => 0,
									'user_id' => intval($var['id']),
									'used_time' => 0,
									'order_id' => 0,
									'emailed' => $emailed,//1：已发成功；0未成功
									'time' => time(),
								);
								$user_bonus_id = $user_bonusdb->add($data);		
							}
						}
					}
				}
			}
			$bonusList = PromotionModel::getBonusList($bonus_id);
		}
		$this->assign('bonusList', $bonusList);
		$this->display('bonus_look_list');
	}
	
	//删除发放的用户红包
	public function user_bonus_delete()
	{
		$bonus_id = intval($_GET['bonus_id']);
		$user_bonus_db = D('user_bonus');
		$user_bonus_info = $user_bonus_db->where('id='.$bonus_id)->find();
		if(! $user_bonus_info){
			$this->error('该用户的红包不存在！', U('promotion/bonus_look_list'));
		}
		$user_bonus_db->delete($bonus_id);
		S('user_bonus_list', NULL);
		$this->success('用户红包删除成功！', U('promotion/bonus_look_list',array('bonus_id'=>$user_bonus_info['bonus_id'])));
	}
	
	//恢复发放的用户红包
	public function user_bonus_regain()
	{
		$bonus_id = intval($_GET['bonus_id']);
		$user_bonus_db = D('user_bonus');
		$user_bonus_info = $user_bonus_db->where('id='.$bonus_id)->find();
		if(! $user_bonus_info){
			$this->error('该用户的红包不存在！', U('promotion/bonus_look_list'));
		}
		$user_bonus_db->where(array('id'=>$bonus_id))->save(array('bonus_sn'=>0,'used_time'=>0));
		S('user_bonus_list', NULL);
		$this->success('红包恢复成功！', U('promotion/bonus_look_list',array('bonus_id'=>$user_bonus_info['bonus_id'])));
	}	
	
	
	//编辑红包类型
	public function bonus_edit()
	{
		$bonus_db = D('bonus_type');
		$bonus_id = intval($_GET['bonus_id']);
		if($_POST['dosubmit']){
			$checkdata['type_name'] = trim($_POST['type_name']);
			if($bonus_id){
				$checkdata['id'] = array('neq', $bonus_id);
			}
			$count = $bonus_db->where($checkdata)->count();
			
			//检测是否存在相同名称的红包
			if($count){
				$this->error('红包类型名称存在，请使用其他名称', U('promotion/bonus_list', array('bonus_id' => $bonus_id)));
			}
			
			$bonus_id = PromotionModel::updateBonusInfo($_POST, $bonus_id);
			if($bonus_id){
				$this->success('红包类型编辑成功！', U('promotion/bonus_list'));
			}else{
				$this->error('红包类型编辑失败！', U('promotion/bonus_list'));
			}
		
		}else{
			$bonusInfo = array();
			if($bonus_id){
				$bonusInfo = $bonus_db->find($bonus_id);
			}
			$this->assign('bonus', $bonusInfo);
			$this->display('bonus_form');
		}
	}
	
	//删除红包类型
	public function bonus_delete()
	{
		$bid = intval($_GET['bonus_id']);
		$bonus_db = D('bonus_type');
		$bonus_info = $bonus_db->where('id='.$bid)->find();
		if(! $bonus_info){
			$this->error('红包类型不存在！', U('promotion/bonus_list'));
		}
		$bonus_db->delete($bid);
		S('bonus_list', NULL);
		$this->success('红包类型删除成功！', U('promotion/bonus_list'));
	}
	
	
	
	//搜索商品
	public function search_product_ajax()
	{
		$cat_id = intval($_GET['cat_id']);
		$brand_id = intval($_GET['brand_id']);
		$keyword = trim($_GET['keyword']);
		
		$result = array(
			'error' => 0,
			'message' => null,
		);
		$where = array(
			'language_id' => C('language_id'),
		);
		if($cat_id){
			//获取所有子类ID
			$cat_ids = CategoryModel::getCategoryChildIds($cat_id, CategoryModel::TYPE_CATEGORY);
			$where['catid'] = array('in', $cat_ids);
		}
		if($brand_id){
			$where['brand_id'] = $brand_id;
		}
		if($keyword){
			$sn_pre = C('product_sn_pre');
			if(is_numeric($keyword)){
				$where['id'] = $keyword;
			}elseif(substr($keyword, 0,2)==$sn_pre){
				$where['sn'] = $keyword;
			}else{
				$where['pri.name'] = array('like', '%'.$keyword.'%');
			}
		}
		
		//去掉已经批发的产品
		$wholesale_db = D('product_wholesale');
		$wholesaleList = $wholesale_db->field('product_id')->select();
		$pids = array();
		if($wholesaleList){
			foreach ($wholesaleList as $wholesale){
				$pids[] = $wholesale['product_id'];
			}
		}
		if($pids){
			$where['id'] = array('not in', join(',', $pids));
		}
		
		$where['is_delete'] = 0;
		$product_db = D('product');
		$product_db->field('id,pri.name');
		$product_db->join('product_items AS pri ON pri.product_id = product.id');
		$product_db->where($where);
		$productList = $product_db->select();
//		echo $product_db->getLastSql();exit;
		if(!$productList){
			$result['error'] = 1;
			$result['message'] = '搜索无产品';
		}else{
			$result['content'] = $productList;
		}
		echo json_encode($result);
	}
}